﻿using System.IO;
using System.Reflection;

namespace TemplateFoundation.Reflection
{
    /// <summary>
    /// Used to read embedded resources from the TemplateFoundation assembly
    /// </summary>
    public static class EmbeddedResourceLoader
    {
        // TODO Ensure thread safety

        /// <summary>
        /// Returns the requested resource from the TemplateFoundation assembly
        /// </summary>
        /// <param name="resource">Resource identifier without the assembly name</param>
        /// <returns></returns>
        internal static string LoadTextFile(string resource)
        {
            return LoadTextFile(resource, typeof(EmbeddedResourceLoader).Assembly);
        }

        /// <summary>
        /// Returns the requested resource from the specified assembly
        /// </summary>
        /// <param name="resource">Resource identifier without the assembly name</param>
        /// <param name="assembly"></param>
        /// <returns></returns>
        public static string LoadTextFile(string resource, Assembly assembly)
        {
            resource = resource.Replace('/', '.');

            if (resource.StartsWith("."))
            {
                resource = resource.Substring(1);
            }

            var file = LoadResource(resource,assembly);

            if (file==null)
            {
                return null;
            }

            var rdr = new StreamReader(file);

            string content = rdr.ReadToEnd();

            // Clean up
            rdr.Close();
            rdr.Dispose();

            return content;
        }

        /// <summary>
        /// Returns the requested resource from the specified assembly
        /// </summary>
        /// <param name="resource">Resource identifier without the assembly name</param>
        /// <param name="assembly"></param>
        /// <returns></returns>
        public static Stream LoadResource(string resource, Assembly assembly)
        {
            resource = resource.Replace('/', '.');

            if (resource.StartsWith("."))
            {
                resource = resource.Substring(1);
            }

            return assembly.GetManifestResourceStream(string.Concat(assembly.ManifestModule.Name.Replace(".DLL", string.Empty).Replace(".dll", string.Empty), ".", resource));
        }
    }
}
